<?php
/**
 * Created by PhpStorm.
 * User: Administrator <email:guoxinlee129@gmail.com>
 * Date: 2020/1/2
 * Time: 21:13
 */

namespace app\common\exception;

use Exception;
use think\exception\HttpException;
use think\facade\Log;

class Handle extends \think\exception\Handle
{
    public $http_code = 500;
    public $error_code = -1;
    public $msg = '系统繁忙，请稍后再试！';
    public $data;

    public function render(Exception $e)
    {
        //var_dump($e);die;
        switch ($e) {
            case $e instanceof HttpException:
                //请求异常
                $this->http_code  = $e->getStatusCode();
                $this->error_code = -1;
                $this->msg        = 'action is not found!';
                break;
            #用户造成的异常 - 数据不存在
            case $e instanceof NotFoundException:
                #用户造成的异常 - 参数异常
            case $e instanceof ParameterFailedException:
                #用户造成的异常 - 基类
            case $e instanceof RuntimeException:
                $this->http_code  = $e->http_code;
                $this->error_code = $e->error_code;
                $this->msg        = $e->msg;
                break;
            #用户造成的异常 - SPL类
            case $e instanceof \RuntimeException:
                $this->http_code  = 400;
                $this->msg        = $e->getMessage();
                $this->error_code = $e->getCode();
                Log::error($e->getMessage());
                break;
            #系统造成的异常
            case $e instanceof \LogicException:
            case $e instanceof \Exception:
                //系统异常 如1/0，记录日志
                //$params = implode(",", \request()->param());
                //new Email("1422476675@qq.com", 'lee', [
                //    "subject" => "系统错误",
                //    "body" => "参数：{$params};详细：{$e->getMessage()}"
                //]);
                $this->msg        = $e->getMessage();
                $this->error_code = $e->getCode();
                $this->http_code  = 500;
                Log::error($e->getMessage());
                break;
            default:
                // 其他错误交给系统处理
                return parent::render($e);
                break;
        }
        $result = [
            'error_code' => $this->error_code,
            'msg'        => $this->msg,
        ];
        if ($this->data !== null) {
            $result['data'] = $this->data;
        }
        return json($result, $this->http_code);
    }
}